package com.example.a13001.shoppingmalltemplate.activitys;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.View.CircleImageView;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.User;
import com.example.a13001.shoppingmalltemplate.modle.UserInfo;
import com.example.a13001.shoppingmalltemplate.mvpview.UserInfoView;
import com.example.a13001.shoppingmalltemplate.presenter.UserInfoPredenter;
import com.example.a13001.shoppingmalltemplate.utils.GlideUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.civ_userinfo_headimg)
    CircleImageView civUserinfoHeadimg;
    @BindView(R.id.et_userinfo_name)
    EditText etUserinfoName;
    @BindView(R.id.tv_userinfo_birthdate)
    TextView tvUserinfoBirthdate;
    @BindView(R.id.rb_userinfo_privacy)
    RadioButton rbUserinfoPrivacy;
    @BindView(R.id.rb_userinfo_man)
    RadioButton rbUserinfoMan;
    @BindView(R.id.rb_userinfo_woman)
    RadioButton rbUserinfoWoman;
    @BindView(R.id.rg_userinfo_gender)
    RadioGroup rgUserinfoGender;
    @BindView(R.id.et_userinfo_address)
    EditText etUserinfoAddress;
    @BindView(R.id.btn_userinfo_commit)
    Button btnUserinfoCommit;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    private int mYear;
    private int mMonth;
    private int mDay;
    private UserInfoPredenter userInfoPredenter = new UserInfoPredenter(UserInfoActivity.this);
    private static final String TAG = "UserInfoActivity";
    private String timeStamp;
    private String code;
    private Map<String,String> map=new HashMap<>();
    private String mGender;
    private JSONObject jsonObject;
    private TimePickerDialog mDialogAll;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        rlRoot.setBackgroundColor(getResources().getColor(R.color.f55555));
        userInfoPredenter.onCreate();
        userInfoPredenter.attachView(userInfoView);
        String safetyCode = MyUtils.getMetaValue(UserInfoActivity.this, "safetyCode");
        code = Utils.md5(safetyCode+Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();
        Log.e(TAG, "onCreate:= "+ code +"time=="+Utils.getTimeStamp());
        userInfoPredenter.getUserInfo(AppConstants.COMPANY_ID, code,Utils.getTimeStamp());
        initData();
    }

    UserInfoView userInfoView = new UserInfoView() {
        //获取用户详细信息
        @Override
        public void onSuccessUserInfo(UserInfo userInfo) {
            Log.e(TAG, "onSuccessUserInfo: "+userInfo.toString() );
            int status=userInfo.getStatus();
            if (status>0){
                GlideUtils.setNetImage(UserInfoActivity.this,AppConstants.INTERNET_HEAD+userInfo.getMemberImg(),civUserinfoHeadimg);
                etUserinfoName.setText(userInfo.getNickName()!=null?userInfo.getNickName():"");
                tvUserinfoBirthdate.setText(userInfo.getBirthday()!=null?userInfo.getBirthday():"");
                String sex=userInfo.getSex(); //性别： 0 保密，1 男，2 女
                if (!TextUtils.isEmpty(sex)) {
                    switch (sex) {
                        case "0":
                            rbUserinfoPrivacy.setChecked(true);
                            break;
                        case "1":
                            rbUserinfoMan.setChecked(true);
                            break;
                        case "2":
                            rbUserinfoWoman.setChecked(true);
                            break;
                    }
                }
                etUserinfoAddress.setText(userInfo.getAddress()!=null?userInfo.getAddress():"");
            }else{
                Toast.makeText(UserInfoActivity.this, ""+userInfo.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }
        //修改会员资料
        @Override
        public void onSuccessModifyUserInfo(CommonResult commonResult) {
            Log.e(TAG, "onSuccessModifyUserInfo: "+commonResult.toString());
            /**
             * {
             "status": 1,
             "chkType": 0,
             "returnMsg": "会员资料更新成功"
             }
             */
           int status= commonResult.getStatus();
           if (status>0){
//               userInfoPredenter.getUserInfo(AppConstants.COMPANY_ID,code,timeStamp);
               onBackPressed();
           }else{
               Toast.makeText(UserInfoActivity.this, ""+commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
           }
        }
        //修改头像
        @Override
        public void onSuccessModifyHeadImg(CommonResult  commonResult) {
            Log.e(TAG, "onSuccessModifyHeadImg: "+commonResult.toString() );
            int status=commonResult.getStatus();
            if (status>0){
                userInfoPredenter.getUserInfo(AppConstants.COMPANY_ID,code,timeStamp);
            }else{
                Toast.makeText(UserInfoActivity.this, ""+commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: "+result.toString() );
        }
    };

    /**
     * 初始化数据源
     */
    private void initData() {
        tvTitleCenter.setText("个人资料");

    }

    @SuppressLint("NewApi")
    @OnClick({R.id.iv_title_back, R.id.tv_userinfo_changeheadima, R.id.btn_userinfo_commit, R.id.tv_userinfo_birthdate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_title_back:
                onBackPressed();
                break;
            //修改头像
            case R.id.tv_userinfo_changeheadima:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .isCamera(true)
                        .enableCrop(true)
                        .circleDimmedLayer(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            //提交
            case R.id.btn_userinfo_commit:
                String realName=etUserinfoName.getText().toString().trim();
                if (TextUtils.isEmpty(realName)){
                    Toast.makeText(this, "请输入真实姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                //性别： 0 保密，1 男，2 女
               if (rbUserinfoMan.isChecked()){
                   mGender = "1";
               }else if(rbUserinfoPrivacy.isChecked()){
                   mGender = "0";
               }else if(rbUserinfoWoman.isChecked()){
                   mGender = "2";
               }else{
                   Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
                   return;
               }
               String birthday=tvUserinfoBirthdate.getText().toString().trim();
                if (TextUtils.isEmpty(birthday)){
                    Toast.makeText(this, "请选择出生日期", Toast.LENGTH_SHORT).show();
                    return;
                }
                String address=etUserinfoAddress.getText().toString().trim();
                if (TextUtils.isEmpty(birthday)){
                    Toast.makeText(this, "请填写地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                map.put("input","memberZsname,memberSex,memberBirthday,memberAddress");
                map.put("memberZsname",realName);
                map.put("memberSex",mGender);
                map.put("memberBirthday",birthday);
                map.put("memberAddress",address);

                userInfoPredenter.modifyUserInfo(AppConstants.COMPANY_ID,code,timeStamp,map);
                break;
            //出生日期
            case R.id.tv_userinfo_birthdate:
                long tenYears = 100L * 365 * 1000 * 60 * 60 * 24L;
                long tenYears1 = 10L * 365 * 1000 * 60 * 60 * 24L;
                mDialogAll = new TimePickerDialog.Builder()
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date d = new Date(millseconds);
                                tvUserinfoBirthdate.setText(sf.format(d));
                            }
                        })
                        .setCancelStringId("取消")
                        .setSureStringId("确定")
                        .setTitleStringId("出生日期选择")
                        .setCyclic(true)
                        .setMinMillseconds(System.currentTimeMillis()-tenYears)
                        .setMaxMillseconds(System.currentTimeMillis())
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.ff2828))
                        .setType(Type.YEAR_MONTH_DAY)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.a32))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.ff2828))
                        .setWheelItemTextSize(12)
                        .build();
                mDialogAll.show(getSupportFragmentManager(), "year_month_day");
//                Calendar ca = Calendar.getInstance();
//                mYear = ca.get(Calendar.YEAR);
//                mMonth = ca.get(Calendar.MONTH);
//                mDay = ca.get(Calendar.DAY_OF_MONTH);
//                new DatePickerDialog(UserInfoActivity.this, onDateSetListener, mYear, mMonth, mDay).show();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String path = selectList.get(0).getCutPath();
                    String path1 = selectList.get(0).getPath();
                    Glide.with(UserInfoActivity.this).load(path).into(civUserinfoHeadimg);
                    Log.e(TAG, "onActivityResult:=== "+"base64"+MyUtils.imageToBase64(path));
                    String ss=MyUtils.imageToBase64(path);
//                    try {
//                        jsonObject = new JSONObject();
//                        jsonObject.put("url", ss);
//
//                        Log.e("aaa", "---jsonObject.toString()----->" + jsonObject.toString());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    userInfoPredenter.modifyHeadImg(AppConstants.COMPANY_ID,code,timeStamp,ss);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }

    /**
     * 日期选择器对话框监听
     */
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("年").append("0").
                            append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("年").append("0").
                            append(mMonth + 1).append("月").append(mDay).append("日").toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("年").
                            append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("年").
                            append(mMonth + 1).append("月").append(mDay).append("日").toString();
                }

            }
            tvUserinfoBirthdate.setText(days);
        }
    };
}
